<template>
  <n-grid cols="1" responsive="screen">
    <n-grid-item>
      <n-form :label-width="120" :model="formValue" ref="formRef">
        <n-form-item label="选择网卡">
          <n-select
            v-model:value="formValue.selectedInterface"
            :options="networkInterfaces"
            placeholder="请选择网卡"
            @update:value="handleInterfaceChange"
          />
        </n-form-item>

        <n-form-item label="IP地址" path="ipAddress">
          <n-input v-model:value="formValue.ipAddress" placeholder="请输入IP地址" />
        </n-form-item>

        <n-form-item label="子网掩码" path="subnetMask">
          <n-input v-model:value="formValue.subnetMask" placeholder="请输入子网掩码" />
        </n-form-item>

        <n-form-item label="网关" path="gateway">
          <n-input v-model:value="formValue.gateway" placeholder="请输入网关" />
        </n-form-item>

        <n-form-item label="DNS" path="dns">
          <n-input v-model:value="formValue.dns" placeholder="请输入DNS服务器地址" />
        </n-form-item>

        <n-form-item label="主路由" path="mainRoute">
          <n-switch v-model:value="formValue.mainRoute" />
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" @click="saveNetworkConfig">保存配置</n-button>
            <n-button @click="resetForm">重置</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useMessage } from 'naive-ui'

const message = useMessage()
const formRef = ref(null)

// 模拟网卡数据
const networkInterfaces = ref([
  { label: 'eth0', value: 'eth0' },
  { label: 'eth1', value: 'eth1' },
  { label: 'wlan0', value: 'wlan0' }
])

const formValue = reactive({
  selectedInterface: '',
  ipAddress: '',
  subnetMask: '',
  gateway: '',
  dns: '',
  mainRoute: false
})

// 切换网卡时加载对应配置
const handleInterfaceChange = (interfaceName: string) => {
  // 这里应该调用API获取选中网卡的配置
  // 模拟数据
  if (interfaceName === 'eth0') {
    Object.assign(formValue, {
      ipAddress: '192.168.1.100',
      subnetMask: '255.255.255.0',
      gateway: '192.168.1.1',
      dns: '8.8.8.8',
      mainRoute: true
    })
  } else {
    Object.assign(formValue, {
      ipAddress: '',
      subnetMask: '',
      gateway: '',
      dns: '',
      mainRoute: false
    })
  }
}

const saveNetworkConfig = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      // 这里应该调用API保存配置
      message.success('网络配置保存成功')
    }
  })
}

const resetForm = () => {
  formRef.value?.restoreValidation()
  handleInterfaceChange(formValue.selectedInterface)
}
</script>
